import 'dart:convert';

import 'package:boss/main.dart';
import 'package:boss/textStyle/text_style.dart';
import 'package:boss/ui/widget/button/fixed_bottom_btn.dart';
import 'package:boss/ui/widget/center_title_app_bar.dart';
import 'package:boss/ui/widget/custom_list_title.dart';
import 'package:boss/ui/widget/form/base_text_form_field.dart';
import 'package:boss/ui/widget/form/select_form_field.dart';
import 'package:boss/ui/widget/image/base_image.dart';
import 'package:boss/ui/widget/label_button.dart';
import 'package:boss/ui/widget/loading/loading.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cupertino_date_picker_fork/flutter_cupertino_date_picker_fork.dart';
import 'package:hi_common/hi_common.dart';
import 'package:router/annotation.dart';

import 'gradeDiscount.dart';

@RouterConfig(MemberDetails.pageName)
class MemberDetails extends StatefulWidget {
  static const pageName = '/memberDetailsPage';

  @Autowired()
  dynamic data;

  MemberDetails({
    this.data,
  });

  @override
  myMemberDetails createState() => myMemberDetails('会员详情');
}

class myMemberDetails extends BaseState<MemberDetails> {
  //是否点击了编辑
  bool _disabled = false;

  dynamic memberInformationObject;

  var resData;

  int id;

  String cardCategorryId; //cardCategorryId

  String status; //状态-1删除0正常1冻结

  //账户余额
  TextEditingController balance;

  //账户积分
  TextEditingController consumeScore;

  //下级所需
  TextEditingController subordinateNeedContent;

  //累计充值金额
  TextEditingController rechargeAward;

  //累计消费金额
  TextEditingController resumeAmount;

  //手机号
  TextEditingController phoneNum;

  //姓名
  TextEditingController name;

  //性别
  int sex = 1;

  //生日
  String birthday = '';

  //身份证
  TextEditingController identityCard;

  //职业
  TextEditingController profession;

  //地址
  TextEditingController address;

  TextEditingController email;

  //开卡时间
  TextEditingController cTime;

  //最后消费时间
  TextEditingController formFieldTextTradeTime;

  myMemberDetails(String pageName) : super(pageName);

  //身份证
  static bool identityId(String str) {
    return RegUtil.identityId.hasMatch(str);
  }

  //邮箱
  static bool emailReg(String str) {
    return RegUtil.emialReg.hasMatch(str);
  }

  @override
  void initState() {
    super.initState();
    balance = TextEditingController();
    consumeScore = TextEditingController();
    subordinateNeedContent = TextEditingController();
    rechargeAward = TextEditingController();
    resumeAmount = TextEditingController();
    phoneNum = TextEditingController();
    name = TextEditingController();
    formFieldTextTradeTime = TextEditingController();
    cTime = TextEditingController();
    identityCard = TextEditingController();
    profession = TextEditingController();
    address = TextEditingController();
    email = TextEditingController();

    id = widget.data["id"] ?? null;

    obtainMemberDetails();

    setState(() {});
  }

  @override
  void dispose() {
    super.dispose();
    balance.dispose();
    consumeScore.dispose();
    subordinateNeedContent.dispose();
    rechargeAward.dispose();
    resumeAmount.dispose();
    phoneNum.dispose();
    name.dispose();
    formFieldTextTradeTime.dispose();
    cTime.dispose();
    identityCard.dispose();
    profession.dispose();
    address.dispose();
    email.dispose();
  }

  //获取当前会员的详情
  obtainMemberDetails() async {
    try {
      Future.delayed(Duration(milliseconds: 0)).then((e) {
        showLoadingToast();
      });

      var res = await api.memberDetail(id.toString());

      if (res.successful()) {
        resData = res.data;

        cardCategorryId = (resData["member"] == null ? null : resData["member"]["cardCategorryId"].toString());
        memberInformationObject = resData["memberRank"];
        status = (resData["member"] == null ? null : resData["member"]["status"].toString());

        balance.text = (resData["member"]["balance"] == null ? '0' : ((resData["member"]["balance"]) / 100).toString());

        consumeScore.text = (resData["member"]["consumeScore"] == null ? '0' : resData["member"]["consumeScore"].toString());
        subordinateNeedContent.text =
            '${memberInformationObject == null ? '' : (memberInformationObject["upgradeConditionType"] == 1 ? '无升级规' : (memberInformationObject["upgradeConditionType"] == 2 ? '充值' : (memberInformationObject["upgradeConditionType"] == 3 ? '消费' : '充值或消费')))} ' +
                (resData["nextLevelAmount"] == null ? '' : (resData["nextLevelAmount"] / 100).toString() + '元');

        rechargeAward.text = (resData["rechargeAward"] == null ? '0' : ((resData["rechargeAward"]) / 100).toString());
        resumeAmount.text = (resData["resumeAmount"] == null ? '0' : ((resData["resumeAmount"]) / 100).toString());
        phoneNum.text = (resData["member"]["phoneNum"] == null ? '' : resData["member"]["phoneNum"].toString());
        name.text = (resData["member"]["name"] == null ? '' : resData["member"]["name"]);
        sex = (resData["member"]["sex"] == null ? null : resData["member"]["sex"]);
        formFieldTextTradeTime.text = (resData["tradeTime"] == null ? '--' : resData["tradeTime"]);
        cTime.text = (resData["member"]["ctime"] == null ? '--' : resData["member"]["ctime"]);

        birthday = (resData["member"]["birthday"] == null ? '' : resData["member"]["birthday"]);
        identityCard.text = (resData["member"]["identityCard"] == null ? '' : resData["member"]["identityCard"]);
        profession.text = (resData["member"]["profession"] == null ? '' : resData["member"]["profession"]);
        address.text = (resData["member"]["address"] == null ? '' : resData["member"]["address"]);
        email.text = (resData["member"]["email"] == null ? '' : resData["member"]["email"]);
        setState(() {});
      } else {
        toast(res.msg);
      }
    } catch (e) {} finally {
      hideLoadingToast();
    }
  }

  //查询所有会员等级list中设置默认的(这个模块不需要)
// queryMemberListDefault() async{
//   showLoadingToast();
//   var res = await queryStoreMemberRank();
//   hideLoadingToast();
//
//   if (res['code'] == HttpRespCode.OK) {
//
//     var dataArr=res["data"] ?? [];
//
//
//     if(dataArr.length!=0){
//
//       var current = dataArr.firstWhere(
//             (item) => item["isDefaultRank"] == 1,
//         orElse: () => null,
//       );
//
//       memberInformationObject=current;
//       cardCategorryId=memberInformationObject["id"];
//       setState(() {});
//     }
//
//
//
//   } else {
//
//     toast( res['msg']);
//   }
//
//
// }

  //修改会员信息(编辑)
  updateMemberFun() async {
    if (phoneNum.text == '') {
      toast("手机号不能为空");

      return null;
    } else {
      if (!RegUtil.testPhone(phoneNum.text.toString())) {
        toast("手机账号格式有误");

        return null;
      }
    }

    if (identityCard != null) {
      if (identityCard.text != '') {
        if (identityId(identityCard.text.toString()) == false) {
          toast("身份证号格式有误");

          return null;
        }
      }
    }

    if (email != null) {
      if (email.text != '') {
        if (emailReg(email.text.toString()) == false) {
          toast("电子邮箱格式有误");

          return null;
        }
      }
    }

    var res = await api.updateMember({
      'id': id,
      'addMemberForm': {
        'cardCategorryId': cardCategorryId,
        'phoneNum': phoneNum.text,
        'name': name.text,
        'sex': sex,
        'birthday': birthday,
        //生日
        'email': email.text,
        'identityCard': identityCard.text,
        //身份证
        'profession': profession.text,
        //职业
        'address': address.text, //地址
      },
    });
    if (res.successful()) {
      toast("编辑完成");
      _disabled = false;
      obtainMemberDetails();
    } else {
      toast(res.msg);
    }
  }

  //冻结和解冻 类型1冻结0正常
  frozenAndThaw(int type) async {
    try {
      Future.delayed(Duration(milliseconds: 0)).then((e) {
        showLoadingToast();
      });

      var res = await api.updateMemberStatus(
        phoneNum: phoneNum.text,
        type: type,
      );

      if (res.successful()) {
        toast("操作成功");
        obtainMemberDetails();
      } else {
        toast(res.msg);
      }
    } catch (e) {} finally {
      hideLoadingToast();
    }
  }

  //卡片折数
  cardRate(str) {
    if (str == null) {
      return '';
    } else {
      if (str["discountCategory"] == 0) {
        return '';
      }
      if (memberInformationObject["extra"] == null) {
        return '';
      } else {
        return ((json.decode(memberInformationObject["extra"])["discountRate"]) / 10).toString() + '折';
      }
    }
  }

  //卡片钱数
  cardMoneyNum(str) {
    if (str == null) {
      return '';
    } else {
      if (memberInformationObject["extra"] == null) {
        return '';
      } else {
        return ((memberInformationObject["targetAmount"] / 100)).toString() + '元 ';
      }
    }
  }

  //iamge 图文
  imageTitle() {
    return Container(
      child: Stack(
        children: <Widget>[
          Padding(
            padding: EdgeInsets.all(
              30.w,
            ),
            child: BaseImage(
              '${"assets/image/memberAdministration1.png"}',
              width: double.infinity,
            ),
          ),
          Positioned(
            top: 50.w,
            left: 0,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Container(
                  padding: EdgeInsets.only(
                    left: 82.w,
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Text(
                        "${memberInformationObject == null ? '- -' : (memberInformationObject["rankName"] == '' ? '- -' : memberInformationObject["rankName"])}",
                        style: TextStyleConstant().white_46,
                      ),
                      SizedBox(
                        height: 22.w,
                      ),
                      Text(
                        "${memberInformationObject == null ? '- -' : (memberInformationObject["discountCategory"] == 0 ? '无优惠' : (memberInformationObject["discountCategory"] == 1 ? '整单折扣' : '菜品会员价'))} ${memberInformationObject == null ? '' : memberInformationObject["discountCategory"] == 1 ? cardRate(memberInformationObject) : ''}",
                        //整单优惠9.8折

                        style: TextStyleConstant().white_28,
                      ),
                    ],
                  ),
                ),
                SizedBox(
                  height: 54.w,
                ),
                Container(
                  margin: EdgeInsets.only(
                    left: 82.w,
                  ),
                  decoration: BoxDecoration(
                    border: memberInformationObject != null
                        ? Border.all(
                            color: Colors.white,
                            width: 1,
                          )
                        : null,
                    borderRadius: BorderRadius.circular(
                      24.w,
                    ),
                  ),
                  height: 48.w,
                  child: Center(
                    child: Text(
                      "   ${memberInformationObject == null ? '' : (memberInformationObject["upgradeConditionType"] == 1 ? '无升级规' : (memberInformationObject["upgradeConditionType"] == 2 ? '充值' : (memberInformationObject["upgradeConditionType"] == 3 ? '消费' : '充值或消费')))}  ${memberInformationObject == null ? '' : memberInformationObject["upgradeConditionType"] == 1 ? '' : cardMoneyNum(memberInformationObject)} ",
                      style: TextStyleConstant().white_26,
                    ),
                  ),
                )
              ],
            ),
          ),
          Positioned(
            right: 0,
            bottom: 62.w,
            child: Padding(
              padding: EdgeInsets.only(
                right: 60.w,
              ),
              child: InkWell(
                onTap: () async {
                  if (_disabled == false) {
                    return null;
                  }
                  var res = await Navigator.pushNamed(context, GradeDiscount.pageName, arguments: {"needBack": true});
                  if (res != null) {
                    memberInformationObject = res;
                    cardCategorryId = memberInformationObject["id"].toString();
                    setState(() {});
                  }
                },
                child: Container(
                  child: Text(
                    "调整等级 >",
                    style: TextStyleConstant().white_22,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  HeaderTitle(String title) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        SizedBox(
          height: 20.w,
        ),
        Row(
          children: <Widget>[
            Container(
              width: 6.w,
              height: 30.w,
              decoration: BoxDecoration(
                color: Color.fromRGBO(87, 112, 246, 1),
                borderRadius: BorderRadius.circular(
                  3.w,
                ),
              ),
            ),
            Text(
              "$title",
              style: TextStyleConstant().appBarTitle,
            ),
          ],
        ),
        SizedBox(
          height: 20.w,
        ),
      ],
    );
  }

  //内容
  contentList() {
    return Container(
      padding: EdgeInsets.only(
        left: 30.w,
        right: 30.w,
      ),
      width: double.infinity,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          HeaderTitle("  会员资产"),

          Row(
            children: <Widget>[
              Expanded(
                child: BaseTextFormField(
                  enabled: false,
                  prefixText: '账户余额',
                  isRequired: false,
                  hintText: '请输入',
                  controller: balance,
                  initialValue: '',
                  onChanged: (value) {
                    setState(() {});
                  },
                ),
              ),
              Text(
                "元",
                style: TextStyleConstant().normal_1_28,
              ),
            ],
          ),

          Row(
            children: <Widget>[
              Expanded(
                child: BaseTextFormField(
                  enabled: false,
                  prefixText: '账户积分',
                  isRequired: false,
                  controller: consumeScore,
                  hintText: '请输入',
                  initialValue: "",
                  onChanged: (value) {
                    setState(() {});
                  },
                ),
              ),
              Text(
                "分",
                style: TextStyleConstant().normal_1_28,
              ),
            ],
          ),

          Row(
            children: <Widget>[
              Expanded(
                child: BaseTextFormField(
                  enabled: false,
                  prefixText: '下级所需',
                  isRequired: false,
                  controller: subordinateNeedContent,
                  hintText: '请输入',
                  initialValue: '',
                  onChanged: (value) {},
                ),
              ),
              Container(),
            ],
          ),

          Row(
            children: <Widget>[
              Expanded(
                child: BaseTextFormField(
                  enabled: false,
                  prefixText: '累计充值金额',
                  controller: rechargeAward,
                  isRequired: false,
                  hintText: '请输入',
                  initialValue: "",
                  onChanged: (value) {
                    setState(() {});
                  },
                ),
              ),
              Text(
                "元",
                style: TextStyleConstant().normal_1_28,
              ),
            ],
          ),

          Row(
            children: <Widget>[
              Expanded(
                child: BaseTextFormField(
                  enabled: false,
                  prefixText: '累计消费金额',
                  isRequired: false,
                  controller: resumeAmount,
                  hintText: '请输入',
                  initialValue: "",
                  onChanged: (value) {
                    setState(() {});
                  },
                ),
              ),
              Text(
                "元",
                style: TextStyleConstant().normal_1_28,
              ),
            ],
          ),

          HeaderTitle("  会员信息"),

          BaseTextFormField(
            enabled: _disabled,
            prefixText: '手机号',
            isRequired: true,
            controller: phoneNum,
            hintText: _disabled == false ? '--' : '请输入',
            initialValue: '',
            onChanged: (value) {
//              phoneNum.text=value;

//              setState(() { });
            },
          ),
          BaseTextFormField(
            enabled: _disabled,
            prefixText: '姓名',
            controller: name,
            isRequired: false,
            hintText: _disabled == false ? '--' : '请输入',
            initialValue: '',
            onChanged: (value) {
              setState(() {});
            },
          ),
          Container(
            child: SelectFormField<String>(
              enabled: _disabled,
              title: '性别',
              hintText: '请选择',
              items: [
                {"name": "男", "key": 1},
                {"name": "女", "key": 2},
              ].map((item) => SelectItem(value: item["key"].toString(), title: item["name"])).toList(),
              value: sex == null ? '1' : sex.toString(),
              onChanged: (value) {
                sex = int.parse(value);
                setState(() {});
              },
            ),
          ),
          Container(
            child: CustomListTitle(
              title: Row(
                children: <Widget>[
                  Text(
                    "生日",
                    style: TextStyleConstant().normal_1_28,
                  ),
                ],
              ),
              trailing: Row(
                children: <Widget>[
                  Text(
                    '${birthday == '' ? "${_disabled == false ? '--' : "请选择"}" : birthday}',
                    style: birthday == "" ? TextStyleConstant().normal_4_28 : TextStyleConstant().normal_1_28,
                  ),
                  if (_disabled == true)
                    Container(
                      margin: EdgeInsets.only(
                        left: 10.w,
                      ),
                      child: BaseImage(
                        'assets/image/arrow_right_icon.png',
                        width: 13.w,
                        height: 30.w,
                      ),
                    ),
                ],
              ),
              onTap: () {
                if (!_disabled) {
                  return null;
                }
                DatePicker.showDatePicker(
                  context,
//                  dateFormat:'YYYY MM dd',
//                minDateTime:DateTime.now(),
                  maxDateTime: DateTime.now(),
                  initialDateTime: DateTime.now(),
                  locale: DateTimePickerLocale.zh_cn,
                  pickerMode: DateTimePickerMode.date,
                  onConfirm: (dateTime, _) {
                    birthday = dateTime.toString().substring(0, 10);
                    setState(() {});
                  },
                );
              },
            ),
          ),
          BaseTextFormField(
            enabled: _disabled,
            prefixText: '身份证',
            controller: identityCard,
            isRequired: false,
            hintText: _disabled == false ? '--' : '请输入',
            initialValue: '',
            onChanged: (value) {
              setState(() {});
            },
          ),
          BaseTextFormField(
            enabled: _disabled,
            prefixText: '职业',
            controller: profession,
            isRequired: false,
            hintText: _disabled == false ? '--' : '请输入',
            initialValue: '',
            onChanged: (value) {
              setState(() {});
            },
          ),
          BaseTextFormField(
            enabled: _disabled,
            prefixText: '地址',
            controller: address,
            isRequired: false,
            hintText: _disabled == false ? '--' : '请输入',
            initialValue: '',
            onChanged: (value) {
              setState(() {});
            },
          ),
          BaseTextFormField(
            enabled: _disabled,
            prefixText: '电子邮箱',
            controller: email,
            isRequired: false,
            hintText: _disabled == false ? '--' : '请输入',
            initialValue: '',
            onChanged: (value) {
              setState(() {});
            },
          ),

          //开卡时间
          BaseTextFormField(
            enabled: false,
            prefixText: '开卡时间',
            isRequired: false,
            controller: cTime,
            hintText: '',
            initialValue: "",
            onChanged: (value) {
              setState(() {});
            },
          ),

          BaseTextFormField(
            controller: formFieldTextTradeTime,
            enabled: false,
            prefixText: '最后消费时间',
            isRequired: false,
            hintText: '',
            initialValue: '',
            onChanged: (value) {
              setState(() {});
            },
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: CenterTitleAppBar(
          title: '会员管理',
          actions: <Widget>[
            if (!_disabled)
              LabelButton(
                title: '编辑',
                padding: EdgeInsets.only(left: 8, top: 2, bottom: 2),
                onTap: () {
                  _disabled = true;
                  toast('开启编辑');
                  setState(() {});
                },
              )
          ],
        ),
        body: Column(
          children: <Widget>[
            Expanded(
              child: SingleChildScrollView(
                child: Column(
                  children: <Widget>[
                    imageTitle(),
                    contentList(),
                  ],
                ),
              ),
            ),
            status != null
                ? FixedBottomBtn(
                    title: _disabled == false ? '${status == '0' ? '冻 结' : '解 冻'}' : '保 存',
                    onTap: () {
                      if (_disabled == false) {
                        if (status == '0') {
                          //冻结
                          frozenAndThaw(1);
                        } else {
                          //解冻
                          frozenAndThaw(0);
                        }
                      } else {
                        //保存
                        updateMemberFun();
                      }
                    },
                    isShowShadow: false,
                  )
                : Container(),
          ],
        ));
  }
}
